from passlib.context import CryptContext
from sqlalchemy.orm import Session

from . import models, schemas

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def get_password_hash(password):
    return pwd_context.hash(password)


def get_user_by_id(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()


def get_user_by_email(db: Session, phone: str):
    return db.query(models.User).filter(models.User.phone == phone).first()


def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()


def create_user(db: Session, user: schemas.UserCreate):
    fake_hashed_password = get_password_hash(user.password)
    db_user = models.User(phone=user.phone, hashed_password=fake_hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def get_items(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Item).offset(skip).limit(limit).all()


def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
    db_item = models.Item(**item.dict(), owner_id=user_id)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item


# 修改数据
def update_item_desc_by_id(db: Session, id: int, desc: str):
    db_item = db.query(models.Item).filter_by(id=id).first()
    db_item.description = desc
    db.commit()
    db.refresh(db_item)
    return db_item


# 批量删除1
def delete_item_by_ownerId1(db: Session, owner_id: int):
    db.query(models.Item).filter_by(owner_id=owner_id).delete(synchronize_session=False)
    db.commit()
    return True


# 批量删除2
def delete_item_by_ownerId2(db: Session, owner_id: int):
    db_items = db.query(models.Item).filter_by(owner_id=owner_id).all()
    [db.delete(item) for item in db_items]
    db.commit()
    return True
